﻿using Mozi.HttpEmbedded;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Mozi.Live.SDP
{
    /// <summary>
    /// 媒体描述信息
    /// </summary>
    public class SDPMedia
    {
        /// <summary>
        /// 媒体类型
        /// </summary>
        public SDPMediaType MediaType { get; set; }
        /// <summary>
        /// 开始端口号
        /// </summary>
        public int Port { get; set; }
        /// <summary>
        /// 端口数量
        /// </summary>
        public int PortCount { get; set; }
        // udp: denotes that the data is transported directly in UDP with no additional framing.
        // RTP/AVP: denotes RTP[RFC3550] used under the RTP Profile for Audio and Video Conferences with Minimal Control[RFC3551] running over UDP.
        // RTP/SAVP: denotes the Secure Real-time Transport Protocol[RFC3711] running over UDP.
        // RTP/SAVPF: denotes SRTP with the Extended SRTP Profile for RTCP-Based Feedback [RFC5124] running over UDP.
        /// <summary>
        /// 传输协议类型
        /// </summary>
        public ProtocolVersion Protocol { get; set; }
        /// <summary>
        /// 传输中荷载的媒体格式，与RTP包相关
        /// </summary>
        public List<int> FormatType { get; set; }
        /// <summary>
        /// 转为文本描述格式
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string result = "";
            if (PortCount > 0)
            {
                result = $"{MediaType} {Port}/{PortCount} {Protocol}";
            }
            else
            {
                result = $"{MediaType} {Port} {Protocol}";
            }
            result += " "+string.Join(" ", FormatType);
            return result;
        }
        /// <summary>
        /// 解析媒体
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static SDPMedia Parse(string data)
        {
            SDPMedia media = new SDPMedia();
            string[] list = data.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

            media.MediaType = SDPMediaType.Get<SDPMediaType>(list[0]);
            if (list[1].IndexOf("/") > 0)
            {
                string[] ports = list[1].Split(new char[] { '/' }, System.StringSplitOptions.RemoveEmptyEntries);
                media.Port = int.Parse(ports[0]);
                media.PortCount = int.Parse(ports[1]);
            }

            media.Protocol = RTSP.RTSPTransportProtocol.Parse(list[2]);

            string[] fmts = new string[list.Length - 3];
            Array.Copy(list, 3, fmts, 0, fmts.Length);

            media.FormatType = fmts.Select(x => int.Parse(x)).ToList();

            return media;
        }

    }

}
